package org.csu.mypetstoreapi.exception;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

//切面，无属性，全局切入
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ConstraintViolationException.class)
    public ModelAndView handleConstraintViolationException(HttpServletRequest request, ConstraintViolationException ex) {
        ModelAndView modelAndView = new ModelAndView();
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login")) {
            modelAndView.setViewName("login");
            modelAndView.addObject("loginMsg", processExceptionMessage(ex.getMessage()));
        } else if (requestURI.contains("register")) {
            modelAndView.setViewName("register");
            modelAndView.addObject("registerMsg", processExceptionMessage(ex.getMessage()));
        }
        return modelAndView;
    }


    //处理e.getMessage()的信息格式
    public String processExceptionMessage(String massage){
        String []msgArray = massage.split(",");
        StringBuilder result = new StringBuilder();
        for (String msg : msgArray){
            String[] tempArray = msg.split(":");
            result.append(tempArray[1]);
        }
        return result.toString();
    }

}
